package com.smedi.ismedi.inmail.core.domain.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.smedi.ismedi.file.dto.request.SignatureRequest;
import com.smedi.ismedi.inmail.core.domain.aggregatemodel.announcement.Announcement;
import com.smedi.ismedi.inmail.core.domain.aggregatemodel.announcement.Receiver;
import com.smedi.ismedi.inmail.core.domain.service.RecordDomainService;
import com.smedi.ismedi.inmail.core.port.adapter.persistence.model.AnnouncementReadRecordRelationshipEntity;
import com.smedi.ismedi.inmail.core.port.adapter.persistence.mybatis.mapper.AnnouncementReadRecordRelationshipMapper;
import com.smedi.ismedi.inmail.core.port.adapter.service.FileRemoteApi;
import com.smedi.ismedi.web.starter.config.AsyncThreadPoolConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务服务实现类
 *
 * @author jiangqinxuan   niuyanling
 * @date 2021/07/27
 */
@Slf4j
@Service
@AllArgsConstructor
public class RecordDomainServiceImpl implements RecordDomainService {
    private final AnnouncementReadRecordRelationshipMapper announcementReadRecordRelationshipMapper;
    private final FileRemoteApi fileRemoteApi;

    @Override
    @Async(AsyncThreadPoolConfig.asyncThreadName)
    public void initRecordsByAnnouncement(Announcement announcement) throws IOException {
        List<Announcement.Statistics> statisticsInInstitution = announcement.getStatisticsInInstitution();
        for (Announcement.Statistics statistics : statisticsInInstitution) {
            this.updateRecordByStatistics(statistics, announcement);
        }
        List<Announcement.Statistics> statisticsInOrganization = announcement.getStatisticsInOrganization();
        for (Announcement.Statistics statistics : statisticsInOrganization) {
            this.updateRecordByStatistics(statistics, announcement);
        }
        List<Announcement.StatisticsInProject> statisticsInProject = announcement.getStatisticsInProject();
        for (Announcement.StatisticsInProject statistics : statisticsInProject) {
            for (Announcement.Statistics statisticsProject : statistics.getProjectStatistics()) {
                this.updateRecordByStatistics(statisticsProject, announcement);
            }
        }
    }

    @Override
    public void updateRecordByStatistics(Announcement.Statistics statistics, Announcement announcement) throws IOException {
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("inmailDate", announcement.getPublishDateTime().toLocalDate().toString().replace("T", " "));
        stringObjectMap.put("inmailName", announcement.getTitle());
        String recordPdf = "";

        List<SignatureRequest> signatureRequests = new ArrayList<>();
        List<RecordDomainServiceImpl.ReceiverRecord> receiverRecords = new ArrayList<>();
        List<Receiver> receivers = statistics.getReceivers();
        for (int i = receivers.size() - 1; i >= 0; i--) {
            Receiver receiver = receivers.get(i);
            RecordDomainServiceImpl.ReceiverRecord receiverRecord = new RecordDomainServiceImpl.ReceiverRecord();
            receiverRecord.setName(receiver.getName());
            if (receiver.getIsRead()) {
                if (ObjectUtils.isNotEmpty(receivers.get(i).getEmployeeNum())) {
                    receiverRecord.setSign(receiver.getName() + "_true");
                    SignatureRequest signatureRequest = new SignatureRequest();
                    signatureRequest.setSignLocation(receivers.get(i).getName() + "_true");
                    signatureRequest.setWorkerId(Long.valueOf(receivers.get(i).getEmployeeNum()));
                    signatureRequests.add(signatureRequest);
                }
                LocalDateTime readTime = receiver.getReadTime();
                receiverRecord.setSignDate(LocalDateTime.of(readTime.toLocalDate(), LocalTime.of(readTime.getHour(), readTime.getMinute(), readTime.getSecond())).toString().replace("T", " "));
            }
            receiverRecords.add(receiverRecord);
        }
        stringObjectMap.put("receiverRecords", receiverRecords);
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder().bind("receiverRecords", policy).build();
        Resource resource = new ClassPathResource("fileTemplate/fileRecord.docx");
        InputStream inputStream = resource.getInputStream();
        XWPFTemplate template = XWPFTemplate.compile(inputStream, config).render(stringObjectMap);

        final File outputFile = File.createTempFile(IdUtil.simpleUUID(), ".docx");
        try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
            template.write(outputStream);

            String recordDoc = fileRemoteApi.uploadFile(outputFile);
            recordPdf = fileRemoteApi.convertToPdf(recordDoc);
            if (CollectionUtils.isNotEmpty(signatureRequests)) {
                for (SignatureRequest signatureRequest : signatureRequests) {
                    signatureRequest.setFileKey(recordPdf);
                }
                recordPdf = fileRemoteApi.postSignatures(signatureRequests);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        } finally {
            Files.deleteIfExists(Paths.get(outputFile.getAbsolutePath()));
        }

        LambdaQueryWrapper<AnnouncementReadRecordRelationshipEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AnnouncementReadRecordRelationshipEntity::getAnnouncementId, announcement.getId());
        lambdaQueryWrapper.eq(AnnouncementReadRecordRelationshipEntity::getSourceFromId, statistics.getSourceFromId());
        lambdaQueryWrapper.eq(AnnouncementReadRecordRelationshipEntity::getSourceFromType, statistics.getSourceFromType());
        AnnouncementReadRecordRelationshipEntity announcementReadRecordRelationshipEntity = announcementReadRecordRelationshipMapper.selectOne(lambdaQueryWrapper);

        if (null == announcementReadRecordRelationshipEntity) {
            announcementReadRecordRelationshipMapper.insert(AnnouncementReadRecordRelationshipEntity.builder()
                    .announcementId(announcement.getId())
                    .recordSignKey(recordPdf)
                    .sourceFromId(statistics.getSourceFromId())
                    .sourceFromType(statistics.getSourceFromType())
                    .sourceFromName(statistics.getName())
                    .build());
        }

        if (null != announcementReadRecordRelationshipEntity) {
            announcementReadRecordRelationshipEntity.setRecordSignKey(recordPdf);
            announcementReadRecordRelationshipMapper.updateById(announcementReadRecordRelationshipEntity);
        }
    }

    @NoArgsConstructor
    @Data
    public class ReceiverRecord {
        private String name;
        private String sign;
        private String signDate;
    }
}
